<template>
  <div class="material-manage">
    <a-table
      bordered
      v-if="inRender"
      :expandIcon="expandIcon"
      :columns="columns"
      :rowKey="record => record.id"
      :data-source="materialTree"
      :default-expand-all-rows="true"
      :pagination="false">
      <template slot="action" slot-scope="text, record">
        <div v-if="record.uplodable && customHandle.materialDirectory && customHandle.materialDirectory.length"><!--目录袋权限-->
          <span v-for="auth in customHandle.materialDirectory" :key="Math.random()" v-if="record.materialType == '1' || getOperateAuth(record, auth) || (isEdit && auth.name === '上传')"><!--materialType为1表示新增目录，默认显示所有按钮-->
            <upload
              class="upload-span"
              :title="auth.name"
              :currentNode="record"
              :project-id="projectId"
              @uploadSuccess="uploadSuccess"
              v-if="auth.name === '上传'"></upload>
            <a-icon
              v-else
              :type="auth.icon"
              :title="auth.name"
              :style="{ color: auth.color }"
              class="m-r-sm cursor-pointer"
              @click="handleClick(auth, record)">
            </a-icon>
          </span>
        </div>
        <div v-if="record.type === 'file' && customHandle.materialFile && customHandle.materialFile.length"><!--文件权限-->
          <span v-for="auth in customHandle.materialFile" :key="Math.random()" v-if="getOperateAuth(record, auth) || isEdit">
            <a-icon
              :type="auth.icon"
              :title="auth.name"
              :style="{ color: auth.color }"
              class="m-r-sm cursor-pointer"
              @click="handleClick(auth, record)">
            </a-icon>
          </span>
        </div>
        <div v-if="record.refId"><!--材料袋权限-->
          <a-icon type="cloud-download" title="打包下载" class="m-r-sm cursor-pointer" @click="downPackage(record)" v-if="isEdit || record.privilege && record.privilege.indexOf('打包下载')!=-1"/>
          <a-icon type="plus" title="创建目录" class="m-r-sm cursor-pointer" @click="createDir(record)" v-if="isEdit || record.privilege && record.privilege.indexOf('创建目录')!=-1"/>
        </div>
      </template>

      <template slot="name" slot-scope="text, record">
        <a-icon
          v-if="record.uplodable"
          class="m-r-sm text-yellow"
          :class="[((record.privilege && record.privilege.indexOf('必传')!=-1) || record.required)?'text-red':'']"
          :type="record.showOpenFolder?'folder-open':'folder'" />
        <span @click="previewNode(record)" @dblclick="previewNode(record)" :title="record.name">{{ record.nick || record.name }}</span>
      </template>

    </a-table>
  </div>

</template>

<script>
  import Upload from '../Upload/Upload'
  import materialApi from '@/api/material'
  import AButton from 'ant-design-vue/es/button/button'
  import moment from 'moment'

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      scopedSlots: { customRender: 'name' }
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTime',
      key: 'uploadTime',
      width: '18%',
      align: 'center',
      customRender: (text, row, index) => {
        return row.uploadTime ? moment(row.uploadTime).format('YYYY-MM-DD HH:mm:ss') : ''
      }
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: '10%',
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      width: '20%',
      scopedSlots: { customRender: 'action' },
      align: 'center'
    }
  ]

  const customHandle = {
    materialDirectory: [
      {
        name: '上传',
        icon: 'upload',
        cb: 'upload'
      },
      {
        name: '创建目录',
        icon: 'plus',
        cb: 'createDir'
      },
      {
        name: '修改目录',
        icon: 'edit',
        cb: 'editDir'
      },
      {
        name: '删除目录',
        icon: 'delete',
        cb: 'delDir'
      }
    ],
    materialFile: [
      {
        name: '浏览',
        icon: 'eye',
        cb: 'preView',
        color: '#3387EA'
      },
      {
        name: '下载',
        icon: 'download',
        cb: 'download',
        color: '#6DD400'
      },
      {
        name: '删除',
        icon: 'delete',
        cb: 'remove',
        color: 'red'
      }
    ]
  }

  export default {
    name: 'MaterialManage',
    data () {
      return {
        columns,
        inRender: false,
        materialTree: [],
        params: this.$route.params,
        showOpenFolder: false,
        customHandle: {},
        query: this.$route.query,
        projectId: this.$route.params.id,
        taskId: this.$route.query.taskId,
        isEdit: this.$route.params.isEdit
      }
    },
    components: {
      AButton,
      Upload
    },
    created () {
    },
    mounted () {
      this.getProjectInfo()
      const _this = this
      this.Event.$on('_REFRESH_MATERIAL_MANAGER_', data => {
        if (data.projectId == _this.projectId) {
          _this.getProjectResourceList()
        }
      })
    },
    computed: {
      getOperateAuth () {
        return (record, btn) => {
          if (this.taskId && parseInt(this.taskId) > 0) {
            return record.privilege ? record.privilege.split(',').includes(btn.name) : false
          }
          return ['浏览', '下载'].includes(btn.name)
        }
      }
    },
    methods: {
      async getProjectInfo () {
        // const d = await projectService.getProjectInfo(this.params.id, this.query.taskId || undefined)
        // this.projectInfo = d.rows[0]
        this.getProjectResourceList()
      },
      getProjectResourceList () {
        const params = {
          projectId: this.projectId,
          taskId: this.taskId || undefined,
          listType: this.taskId ? 1 : 0 // 0 项目；1 环节；2 业务
        }
        materialApi.getMaterialList(params).then(d => {
          const list = d.map(item => {
            return item.categoryInstDTO
          })
          this.formatData(list)
          this.projectResourceList = list
          this.materialTree = this.projectResourceList
          this.initMaterialAuth()
        })
      },
      formatData (list, privilege) {
        list.forEach(item => {
          if (!item.privilege && privilege) {
            item.privilege = privilege
          }
          if (item.files && item.files.length > 0) {
            const files = this._.cloneDeep(item.files).map(file => {
              file.privilege = item.privilege
              return file
            })
            if (item.children) {
              item.children = item.children.concat(files)
            } else {
              item.children = files
            }
          }
          if (item.children) {
            this.formatData(item.children, item.privilege)
          }
        })
      },
      download (file) {
        const params = {
          materialFileId: file.id,
          fileName: file.name,
          mimetype: 'download'
        }
        materialApi.downloadMaterial(params)
      },
      downPackage (record) {
        const params = {
          projectId: this.projectId,
          categoryInstIds: record.id// 不传，下载整个项目材料
        }
        materialApi.downPackage(params)
      },
      preView (file) {
        this.$emit('addTab', { type: 'file', file: file })
      },
      deleteFile (file) {
        this.$confirm({
            content: '是否删除选中的文件：【' + file.name + '】?',
            okType: 'danger',
            onOk: () => {
              const _params = {
                materialFileIds: file.id
              }
              materialApi.deleteMaterial(_params).then(resp => {
                this.getProjectResourceList()
                this.$success({
                  content: '删除成功'
                })
                this.Event.$emit('FORMRIGHT_MATERIAL_REFRESH', { projectId: this.projectId })
              })
            }
        })
      },
      uploadSuccess (data) {
        this.getProjectResourceList()
        this.Event.$emit('FORMRIGHT_MATERIAL_REFRESH', { projectId: this.projectId })
      },
      expandIcon (props) {
        if (props.record.type !== 'file') {
          if (props.expanded) {
            props.record.showOpenFolder = true
            return <a-icon type="down" class="m-r-sm" style="color:#9C9C9C;" onClick={e => {
              props.record.showOpenFolder = !props.record.showOpenFolder
              props.onExpand(props.record, e)
            }}/>
          } else {
            props.record.showOpenFolder = false
            return <a-icon type="right" class="m-r-sm" style="color:#9C9C9C;" onClick={e => {
              props.record.showOpenFolder = !props.record.showOpenFolder
              props.onExpand(props.record, e)
            }}/>
          }
        } else {
          return <span class="m-r-sm"></span>
        }
      },
      initMaterialAuth () {
        if (this.taskId || this.isEdit) {
          this.customHandle = customHandle
        } else {
          this.customHandle = {
            materialFile: [
              {
                name: '下载',
                icon: 'download',
                cb: 'download',
                color: '#6DD400'
              },
              {
                name: '浏览',
                icon: 'eye',
                cb: 'preView',
                color: '#3387EA'
              }
            ]
          }
        }
      },
      handleClick (item, record) {
        switch (item.name) {
          case '下载': {
            this.download(record)
            break
          }
          case '浏览': {
            this.$emit('addTab', { type: 'file', file: record })
            break
          }
          case '删除': {
            this.deleteFile(record)
            break
          }
          case '创建目录': {
            this.createDir(record)
            break
          }
          case '修改目录': {
            this.editDir(record)
            break
          }
          case '删除目录': {
            this.delDir(record)
            break
          }
        }
      },
      createDir (record) {
        var _this = this
        layer.prompt({
title: '添加目录',
formType: 2,
yes: function (index, layero) {
          layer.close(index)
          var dirName = layero.find('.layui-layer-input').val()
          const _params = {
            projectId: _this.projectId,
            parentId: record.id,
            parentType: record.refId ? 0 : 1, // 0 材料袋；1 目录
            dirName: dirName,
            sortNo: record.children ? record.children.length : 1
          }
          materialApi.addDirectory(_params).then(resp => {
            _this.getProjectResourceList()
            _this.$success({
              content: '添加成功'
            })
            _this.Event.$emit('FORMRIGHT_MATERIAL_REFRESH', { projectId: _this.projectId })
          })
        }
})
      },
      editDir (record) {
        var _this = this
        layer.prompt({
title: '修改目录',
formType: 2,
yes: function (index, layero) {
            layer.close(index)
            var dirName = layero.find('.layui-layer-input').val()
          const _params = {
            projectId: _this.projectId,
            dirInstId: record.id,
            dirName: dirName
          }
          materialApi.editDirName(_params).then(resp => {
            _this.getProjectResourceList()
            _this.$success({
              content: '修改成功'
            })
            _this.Event.$emit('FORMRIGHT_MATERIAL_REFRESH', { projectId: _this.projectId })
          })
        }
})
      },
      delDir (record) {
        const _params = {
          projectId: this.projectId,
          dirInstId: record.id
        }
        materialApi.deleteMaterialDir(_params).then(resp => {
          this.getProjectResourceList()
          this.$success({
            content: '删除成功'
          })
          this.Event.$emit('FORMRIGHT_MATERIAL_REFRESH', { projectId: this.projectId })
        })
      },

      previewNode (item) {
        if (item.type === 'file') {
          this.$emit('addTab', { type: 'file', file: item })
        }
      }
    },
    watch: {
      materialTree (val) {
        this.inRender = true
      }
    }
  }
</script>

<style scoped lang="less">
  .material-manage {
    background: #fff;
    padding: 10px;
    overflow: auto;
    /deep/ .ant-table-thead > tr > th {
      text-align: center;
    }

    /deep/  .ant-table-thead > tr > th,
    /deep/ .ant-table-tbody > tr > td{
      padding: 8px 12px;
    }
    .text-yellow{
      color: orange;
    }
    .text-red{
      color: red  !important;
    }
    .upload-span{
      display: inline-block;
      margin-right: 10px
    }
  }
</style>
